package cn.kgc.mcartoon.interceptor;

import cn.kgc.mcartoon.dto.ResultJson;
import cn.kgc.mcartoon.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //是否登录
        boolean isLogin = false;

        //拦截器获取请求头信息
        String authHeader = request.getHeader("Authorization");
        //判断获取到的请求头是否为空，后者是否以Christopher开始
        if(StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")) {
            // 截取token，
            final String token = authHeader.substring(7);
            // 解析token
            Claims claims = jwtUtil.parseJWT(token);
            if(claims != null) {
                // 是否登录
                isLogin  = (Boolean) claims.get("isLogin");
//
            }

        }else {
            //设置响应的字符编码格式
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            //返回状态码401，代码未授权
            response.setStatus(401);
            response.getWriter().write(ResultJson.error("请先登录后访问").toString());
        }



        return isLogin;
    }




}
